/*
 *
 * FileName: SCMClientFactory.java
 * Author:   wx:fdzhangc
 * Date:     2021/11/24 10:18
 * Description: //模块目的、功能描述
 * History: //修改记录
 * <author>      <time>      <version>    <desc>
 * 修改人姓名    修改时间    版本号       描述
 */
package com.zhangc.zcscm.client;

import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 功能描述:<br>
 *
 * @author wx:fdzhangc
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
public abstract class SCMClientFactory {
    private static final Map<String, SCMClient> clients = new ConcurrentHashMap();

    public SCMClientFactory() {
    }

    public static SCMClient getSCMClient() throws SCMException {
        return getSCMClient(SCMConfiguration.CONFIG_FILE);
    }

    public static void setConfigFilePath(String path) {
        SCMConfiguration.CONFIG_FILE = path;
    }

    public static SCMClient getSCMClient(String configFilePath) throws SCMException {
        SCMClient client = (SCMClient) clients.get(configFilePath);
        if (client != null) {
            return client;
        } else {
            synchronized (clients) {
                client = (SCMClient) clients.get(configFilePath);
                if (client == null) {
                    SCMConfiguration config = SCMConfiguration.getInstance(configFilePath);
                    client = new SCMClientImpl(config);
                    clients.put(configFilePath, client);
                }

                return (SCMClient) client;
            }
        }
    }

    public static void destroy(SCMClient client) {
        synchronized (clients) {
            String key = null;
            Iterator i$ = clients.entrySet().iterator();

            while (i$.hasNext()) {
                Map.Entry<String, SCMClient> entry = (Map.Entry) i$.next();
                if (client == entry.getValue()) {
                    key = (String) entry.getKey();
                    break;
                }
            }

            if (key != null) {
                clients.remove(key);
            }

            client.destroy();
        }
    }

    public static void destroy(String configFile) {
        synchronized (clients) {
            SCMClient client = (SCMClient) clients.remove(configFile);
            if (client != null) {
                client.destroy();
            }

        }
    }

    public static void shutdown() {
        synchronized (clients) {
            Iterator i$ = clients.values().iterator();

            while (i$.hasNext()) {
                SCMClient client = (SCMClient) i$.next();
                client.destroy();
            }

            clients.clear();
        }
    }
}
